#!/bin/bash

set -e -u -x

PACKAGE_DIR=/var/vcap/packages/postgresql_9.3
JOB_DIR=/var/vcap/jobs/postgresql

STORE_DIR=/var/vcap/store
DATA_DIR=$STORE_DIR/postgresql

RUN_DIR=/var/vcap/sys/run/postgresql
LOG_DIR=/var/vcap/sys/log/postgresql

# external_pid_file in postgresql.conf takes care of
# overwriting $PIDFILE with actual DB server pid
PIDFILE=$RUN_DIR/postgres.pid

HOST="<%= p("bind_ip") %>"
PORT="<%= p("bind_port") %>"
LD_LIBRARY_PATH=$PACKAGE_DIR/lib

source /var/vcap/packages/pid_utils/pid_utils.sh

case "$1" in
  start)
    pid_guard $PIDFILE "PostgreSQL"

    mkdir -p $RUN_DIR
    chown vcap:vcap $RUN_DIR

    sysctl -w "kernel.shmmax=284934144"

    if [ ! -d $LOG_DIR ]; then
      mkdir -p $LOG_DIR
      chown vcap:vcap $LOG_DIR
    fi

    if [ ! -d $DATA_DIR -o ! -f $DATA_DIR/postgresql.conf ]; then
      mkdir -p $DATA_DIR
      chown vcap:vcap $DATA_DIR

      # initdb creates data directories
      su - vcap -c "$PACKAGE_DIR/bin/initdb -E utf8 --locale en_US.UTF-8 -D $DATA_DIR"

      mkdir -p $DATA_DIR/pg_log
      chown vcap:vcap $DATA_DIR/pg_log
    fi

    cp $JOB_DIR/config/{postgresql,pg_hba}.conf $DATA_DIR
    chown vcap:vcap $DATA_DIR/{postgresql,pg_hba}.conf

    echo "Starting PostgreSQL: "
    su - vcap -c "$PACKAGE_DIR/bin/pg_ctl -o \"-h $HOST -p $PORT\" \
                  -w start -D $DATA_DIR -l \"$DATA_DIR/pg_log/startup.log\""

    echo "PostgreSQL started successfully"

    echo "Creating databases and roles..."
    <% p("databases", []).each do |db| %>
      echo "Trying to create role <%= db["role"] %>..."

      $PACKAGE_DIR/bin/psql -U vcap -p $PORT -d postgres \
                            -c "CREATE ROLE \"<%= db["role"] %>\"" ||
        echo "Role already exists?"

      echo "Setting password for role <%= db["role"] %>..."
      $PACKAGE_DIR/bin/psql -U vcap -p $PORT -d postgres \
                            -c "ALTER ROLE \"<%= db["role"] %>\" \
                                WITH LOGIN PASSWORD '<%= db["password"] %>'"

      echo "Trying to create database <%= db["name"] %>..."

      su - vcap -c "$PACKAGE_DIR/bin/createdb \"<%= db["name"] %>\" -p $PORT" ||
        echo "Database already exists?"
    <% end %>

    ;;

  stop)
    echo "Stopping PostgreSQL: "
    su - vcap -c "$PACKAGE_DIR/bin/pg_ctl stop -m fast -w -D $DATA_DIR"
    wait_pidfile $PIDFILE 1

    ;;

  status)
    su - vcap -c "$PACKAGE_DIR/bin/pg_ctl status -D $DATA_DIR"

    ;;

  *)
    echo "Usage: $0 {start|stop|status}"
    exit 1

    ;;

esac
